package com.dq.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dq.commonutils.pojo.DqException;
import com.dq.order.entity.Order;
import com.dq.order.entity.PayLog;
import com.dq.order.properties.WxProperties;
import com.dq.order.service.OrderService;
import com.dq.order.service.PayLogService;
import com.dq.order.mapper.PayLogMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dq.order.utils.HttpClient;
import com.github.wxpay.sdk.WXPayUtil;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付日志表(TPayLog)表服务实现类
 *
 * @author Dq
 * @since 2022-08-17 15:25:42
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog>  implements PayLogService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayLogMapper payLogMapper;

    @Autowired
    private WxProperties wxProperties;

    //创建支付二维码
    @Override
    public Map<String, Object> createQrCode(String orderNo) {
        /**
         * 1. 根据订单号查询信息
         * 2. 利用map设置一些支付基本信息
         * 3. 发送httpclient请求 传递xml格式
         * 4. 得到发送请求返回结果  jasn转化
         */
        try {
            Order orderInfo = orderService.getOrderInfoById(orderNo);
            //2、使用map来设置生成二维码需要的参数
            HashMap<String, String> map = new HashMap<>();
            map.put("appid",wxProperties.getAppid());//支付id
            map.put("mch_id", wxProperties.getPartner());//商户号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//生成随机的字符串，让每次生成的二维码不一样
            map.put("body", orderInfo.getCourseTitle());//生成二维码的名字
            map.put("out_trade_no", orderNo);//二维码唯一的标识
            map.put("total_fee",orderInfo.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");//支付金额
            map.put("spbill_create_ip", "127.0.0.1");//现在进行支付的ip地址，实际项目使用项目的域名
            map.put("notify_url",wxProperties.getNotifyurl() );//支付后回调地址
            map.put("trade_type", "NATIVE");//支付类型，NATIVE:根据价格生成二维码

            //发送httpclient,传递参输xml
            HttpClient client = new HttpClient(wxProperties.getUnifiedorderUrl());
            client.setXmlParam(WXPayUtil.generateSignedXml(map,wxProperties.getPartnerkey()));
            client.setHttps(true);
            client.post();

            //返回的xml的String类型 需要转化为map
            String content = client.getContent();
            Map<String, String> clientMap= WXPayUtil.xmlToMap(content);

            //最终返回数据封装
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("out_trade_no",orderNo);
            resultMap.put("course_id",orderInfo.getCourseId());
            resultMap.put("total_fee",orderInfo.getTotalFee());
            resultMap.put("result_code",clientMap.get("result_code")); //二维码操作状态码
            resultMap.put("code_url",clientMap.get("code_url")); //二维码地址
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new DqException(20002,"生成二维码失败");
        }
    }
    //查询支付状态
    @Override
    public Map<String, String> queryWxPayStatu(String orderNo) {
        /**
         * 1. 封装Map参数
         * 2. 发送httpclient请求获取返回信息
         */
        try {
            HashMap<String, String> map = new HashMap<>();
            map.put("appid",wxProperties.getAppid());//支付id
            map.put("mch_id", wxProperties.getPartner());//商户号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//生成随机的字符串，让每次生成的二维码不一样
            map.put("out_trade_no", orderNo);//二维码唯一的标识

            //发送httpclient,传递参输xml
            HttpClient client = new HttpClient(wxProperties.getOrderqueryUrl());
            client.setXmlParam(WXPayUtil.generateSignedXml(map,wxProperties.getPartnerkey()));
            client.setHttps(true);
            client.post();

            //获取请求返回的内容
            String content = client.getContent();
            Map<String, String> contentMap = WXPayUtil.xmlToMap(content);
            return contentMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //更新订单状态并插入付款信息
    @Override
    public void updateOrderStateAndInsertPayInfo(Map<String, String> resultMap) {
        //根据订单号查询订单
        String out_trade_no = resultMap.get("out_trade_no"); //查询订单号
        Order orderInfo = orderService.getOrderInfoById(out_trade_no);

        //判断订单状态 如果是一 则已经购买了
        if (orderInfo.getStatus().intValue()==1){
            return;
        }
        orderInfo.setStatus(1);
        orderService.updateById(orderInfo);

        //添加支付记录
        PayLog payLog = new PayLog();
        payLog.setOrderNo(out_trade_no);
        payLog.setPayType(1);
        payLog.setTotalFee(orderInfo.getTotalFee());
        payLog.setTradeState(resultMap.get("trade_state")); //支付状态
        payLog.setTransactionId(resultMap.get("transaction_id"));
        payLog.setAttr(JSONObject.toJSONString(resultMap));
        payLog.setPayTime(new Date());
        int insert = payLogMapper.insert(payLog);//插入支付信息
        System.out.println(insert);
    }
}